package com.zixi.beverage_order.service.customer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zixi.beverage_order.mapper.CustomerMapper;
import com.zixi.beverage_order.pojo.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.sql.Timestamp;


@Service
public class WxLoginServiceImpl implements WxLoginService{

    private String openid;

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Customer Code2OpenId(String code) {

        String appID = "wx67580cc7f111ff99";
        String secret = "cdbc80fc7695343af560a905b0f6dd39";
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" +
                appID +
                "&secret=" +
                secret +
                "&js_code=" +
                code +
                "&grant_type=authorization_code";
        String jsonData = this.restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(jsonData);
        //得到用户的sessionkey和openid
        if (jsonData == null) {
            return null;
        } else {
            this.openid = (String) jsonObject.get("openid");
            QueryWrapper<Customer> wrapper = new QueryWrapper<>();
            Customer selectByWxid = customerMapper.selectOne(wrapper.eq("wxid", openid));
            //没有的话新建一个传回
            if (selectByWxid == null) {
                //插入
                Customer newCustomer = new Customer();
                newCustomer.setNickname("未授权昵称和头像！");
                newCustomer.setWxid(openid);
                newCustomer.setRewardstar(0L);
                Timestamp date = new Timestamp(System.currentTimeMillis());
                newCustomer.setSignupdate(date);
                customerMapper.insert(newCustomer);
                return newCustomer;
            } else {
                //查找数据库有没有这个id 有的话直接调取对象传回
                return selectByWxid;
            }
        }
    }

    @Override
    public Customer SetCustomerInfo(String nickName,String avatarUrl){//授权了昵称和头像更新数据
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        Customer selectByWxid = customerMapper.selectOne(wrapper.eq("wxid", openid));
        selectByWxid.setNickname(nickName);
        selectByWxid.setPicdata(avatarUrl);
        //更新数据库
        customerMapper.update(selectByWxid,wrapper.eq("wxid",openid));
        return selectByWxid;
    }
}
